package com.xin.mmall.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xin.mmall.entity.User;
import com.xin.mmall.service.CartService;
import com.xin.mmall.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;
import java.io.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 吴玉鑫
 * @since 2021-05-13
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private CartService cartService;
    @RequestMapping("/login")
    public String login(String loginName, String passWord, HttpSession session){
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("login_name",loginName);
        userQueryWrapper.eq("password",passWord);
        User user = userService.getOne(userQueryWrapper);
        if (user==null){
            return "login";
        }
        else{
            session.setAttribute("user",user);
            return "redirect:/productCategory/list";
        }
    }

    @GetMapping("/info")
    public ModelAndView info(HttpSession session){
        User user = (User) session.getAttribute("user");
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("userInfo");
        modelAndView.addObject("cartList",cartService.findAllCartVOByUserId(user.getId()));
        return modelAndView;
    }


    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }

    @PostMapping("/register")
    public String register(User user, Model model){

        try {
           userService.save(user);
        } catch (Exception e) {
            model.addAttribute("error",user.getLoginName()+"已存在，请重新输入！！！");
            System.out.println("error");
            return "register";
        }
        return "login";
    }

    @PostMapping("/upload")
    public ModelAndView upload(HttpSession session, HttpServletRequest request){
        User user = (User) session.getAttribute("user");
        String loginName = user.getLoginName();
        try {
            Part part = request.getPart("photo");
            //获取文件名
            String fileName = part.getSubmittedFileName();

            //获取数据的流
            InputStream inStream = part.getInputStream();

            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            //创建一个Buffer字符串
            byte[] buffer = new byte[1024];
            //每次读取的字符串长度，如果为-1，代表全部读取完毕
            int len = 0;
            //使用一个输入流从buffer里把数据读取出来
            while( (len=inStream.read(buffer)) != -1 ){
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
                outStream.write(buffer, 0, len);
            }
            //关闭输入流
            inStream.close();
            //把outStream里的数据写入内存
            //得到图片的二进制数据，以二进制封装得到数据，具有通用性
            byte[] data = outStream.toByteArray();
            //new一个文件对象用来保存图片，默认保存当前工程根目录
            File imageFile = new File("F:/IDEA/IDEA_Projects/mmall/src/main/resources/static/images/head"+loginName+".jpg");
            //创建输出流
            FileOutputStream fileOutStream = new FileOutputStream(imageFile);
            //写入数据
            fileOutStream .write(data);
            //更新用户的头像
            UpdateWrapper<User> userUpdateWrapper = new UpdateWrapper<>();
            userUpdateWrapper.eq("id",user.getId())
                    .set("file_name","head"+loginName+".jpg");
            //更改user的头像
            user.setFileName("head"+loginName+".jpg");
            userService.update(userUpdateWrapper);
            session.removeAttribute("user");
            session.setAttribute("user",user);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("userInfo");
        modelAndView.addObject("cartList",cartService.findAllCartVOByUserId(user.getId()));
        return modelAndView;
    }
}

